package cn.springcloud.fix.demo.io;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ThreadPoolExecutor;

public class WriteState implements HandlerState {

    @Override
    public void changeState(Handler h) {
        h.setState(new ReadState());
    }

    @Override
    public void handle(Handler h, SelectionKey sk, SocketChannel sc, ThreadPoolExecutor pool) throws IOException { // send()
        String str = "Your message has sent to " + sc.socket().getLocalSocketAddress().toString() + "\r\n";
        ByteBuffer buf = ByteBuffer.wrap(str.getBytes()); // wrap自动把buf的position设为0，所以不需要再flip()

        while (buf.hasRemaining()) {
            sc.write(buf); // 回传给client回传字符串，发送buf的position位置 到limit位置为止之间的內容
        }

        // 三步一体
        h.setState(new ReadState()); // 改变状态(SENDING->READING)
        sk.interestOps(SelectionKey.OP_READ); // 通过key改变通道注册的事件
        sk.selector().wakeup(); // 使一个阻塞住的selector操作立即返回
    }
}
